package com.watertek.bdcenter.bdcode.service.impl;

import com.watertek.bdcenter.bdcode.dao.GridIndexTablesDao;
import com.watertek.bdcenter.bdcode.entity.AnJian;
import com.watertek.bdcenter.bdcode.mapper.AnJianMapper;
import com.watertek.bdcenter.bdcode.service.GridIndexTablesService;
import com.watertek.bdcenter.bdcode.util.HBaseUtil;
import com.watertek.geosot.GCode1D;
import com.watertek.geosot.GeoSOT;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GridIndexTablesServiceImpl extends AbstractService implements GridIndexTablesService {
    @Autowired
    private GridIndexTablesDao gridIndexTablesDao;

    @Autowired
    private AnJianMapper anJianMapper;

    /**
     * 添加GridIndexTables对象
     * @param rowName
     * @param familyName
     * @param qualifier
     * @param value
     */
    @Override
    public void put(String rowName, String familyName, String qualifier, byte[] value) {
        gridIndexTablesDao.put(rowName, familyName, qualifier, value);
    }

    /**
     * 从业务数据库中依次获取每个表格的每条记录的经纬度，加上层级（暂时写死在config.properties文件中），
     * 将其转换为北斗网格码，最后将业务数据的id和北斗网格码存储到HBase中。
     */
    @Override
    public void loadBdCode() {
        List<AnJian> anJianList=anJianMapper.findAll();
        if(null!=anJianList && anJianList.size()>0){
            List<Mutation> mutationList = new ArrayList<Mutation>();
            for(AnJian anJian : anJianList){
                GCode1D orgGCode1D= GeoSOT.getGCode1DOfPoint(anJian.getLon(), anJian.getLat(), Integer.parseInt(POINT_TO_CODE_LAYER));
                String code=orgGCode1D.getCode().toString();
                String id=anJian.getId().toString();

                Put p = new Put(Bytes.toBytes(HBaseUtil.generateRowKey()));
                // 注意：Bytes.toBytes的参数必须是String类型，否则在HBase中会以16进制显示
                p.add(Bytes.toBytes("entity"), Bytes.toBytes("data-object-id"), Bytes.toBytes(id));
                p.add(Bytes.toBytes("entity"), Bytes.toBytes("data-category"), Bytes.toBytes(""));
                p.add(Bytes.toBytes("entity"), Bytes.toBytes("bd-code"), Bytes.toBytes(code));
                // 此处需要添编码的加时间
                mutationList.add(p);
            }
            gridIndexTablesDao.batchPut(mutationList);
        }
    }
}
